// src/stores/together.ts
import { defineStore } from 'pinia'

export interface CardItem {
  id: number
  title: string
  image: string
  members: number
  updateTime: string
}
type PartialCard = Omit<CardItem, 'id'>

const LS_KEY = 'together_cards'

// 固定默认三项（id 固定，后续新增用 Date.now()，排序时新内容会排在前面）
const DEFAULT_CARDS: CardItem[] = [
  {
    id: 1,
    title: '其他人的城堡',
    image: '/together/together_1.png', // ⚠️ 放 public 下用绝对路径，不要写 "public/"
    members: 3,
    updateTime: '2小时前更新',
  },
  {
    id: 2,
    title: '小白和小鸡毛之家',
    image: '/together/together_2.png',
    members: 1,
    updateTime: '昨天更新',
  },
  {
    id: 3,
    title: '读心理学读成研究对象了',
    image: '/together/together_3.png',
    members: 2,
    updateTime: '昨天更新',
  },
]

export const useTogetherStore = defineStore('together', {
  state: () => ({
    cardList: [] as CardItem[],
    hydrated: false,
  }),
  actions: {
    hydrateFromLocal() {
      if (this.hydrated) return
      try {
        const raw = localStorage.getItem(LS_KEY)
        if (raw) {
          const saved: CardItem[] = JSON.parse(raw)

          // 将默认项并入（按 id 去重，若历史数据里没有则补上）
          const map = new Map<number, CardItem>()
          for (const it of saved) map.set(it.id, it)
          for (const def of DEFAULT_CARDS) {
            if (!map.has(def.id)) map.set(def.id, def)
          }
          this.cardList = Array.from(map.values())
        } else {
          // 首次：直接落库默认项
          this.cardList = DEFAULT_CARDS.slice()
          this.persist()
        }

        // 统一按 id 倒序（新加的用 Date.now()，会自然在前面）
        this.cardList.sort((a, b) => b.id - a.id)
      } catch {
        this.cardList = DEFAULT_CARDS.slice()
        this.cardList.sort((a, b) => b.id - a.id)
        this.persist()
      } finally {
        this.hydrated = true
      }
    },

    addCard(card: PartialCard) {
      const item: CardItem = {
        id: 1756645784074, // 新内容更大 id → 会排在前面
        ...card,
      }
      this.cardList.unshift(item)
      // 双保险：统一维持倒序
      this.cardList.sort((a, b) => b.id - a.id)
      this.persist()
    },

    persist() {
      localStorage.setItem(LS_KEY, JSON.stringify(this.cardList))
    },

    clearAll() {
      // 清空后恢复为默认三项
      this.cardList = DEFAULT_CARDS.slice()
      this.cardList.sort((a, b) => b.id - a.id)
      this.persist()
    },
  },
})
